<template>
  <div class="l-p-c-root" v-loading="loading">

    <div class="query-container" :style="queryContainerStyle">
      <query-select class="map-q-item" @submit="attQuery" :select-type-list="selectTypeList"></query-select>
    </div>

    <lark-map @loaded="load" ref="mmap" :map-config="bufferMapConfig" :query-back-fun="queryBackFun"
              :before-query="beforeQuery"
              :after-query="afterQuery"></lark-map>

    <div style="display: none">
      <el-tabs v-model="activeName" ref="tabs">
        <el-tab-pane v-for="(item, index) in tabsData" :key="`${item.layerId}_${index}`" :label="item.layerName"
                     :name="item.layerId.toString()">
          <div class="table-container">
            <lark-value-table :data="item.tableData" width="100%"
                              height="100%" :column-number="2"></lark-value-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, computed } from '@vue/composition-api'
  import { Message, MessageBox } from 'element-ui'
  import store from '@/store'
  import router from '@/router'
  import mapConfig from '../../../../../datas/labConfig'
  import querySelect from '@/components/ServiceComponents/querySelect/index'
  import {
    queryResultsByUrls,
    highlightByGeometryList,
    getGeometryListByQueryResult,
    getTabsDataByQueryResult,
    getOnlyResByQueryResult,
    removeHighlight
  } from 'lark-map'
  import { MathUtil } from 'lark-utils'

  export default {
    name: 'index',
    props: {},
    components: {
      querySelect
    },
    setup(props, content) {

      let {} = props

      const queryContainerStyle = computed(() => {
        return { left: `${(window.innerWidth - 380) / window.innerWidth * 100 / 2}%` }
      })

      const data = reactive({
        bufferMapConfig: mapConfig,
        loading: true,
        queryContainerStyle,
        selectTypeList: [
          {
            icon: 'el-icon-office-building',
            label: '种质资源',
            value: 'zzzy',
            disabled: false
          },
          {
            icon: 'el-icon-office-building',
            label: '实验室',
            value: 'sys',
            disabled: false
          },
          {
            icon: 'el-icon-office-building',
            label: '土壤',
            value: 'tr',
            disabled: true
          },
          {
            icon: 'el-icon-office-building',
            label: '水分',
            value: 'sf',
            disabled: true
          }
        ],
        activeName: '',
        tabsData: []
      })

      const queryBackFun = (res, mapPoint) => {
        let { view } = data

        let onlyRes = getOnlyResByQueryResult({ res, mapPoint })

        if (!onlyRes?.length) {
          removeHighlight()
          return
        }

        let attList = getTabsDataByQueryResult(onlyRes)

        data.tabsData = attList.map(item => {

          let { tableData, layerId, layerName } = item

          let [currentTableData] = tableData

          let itemRes = {
            layerId: `${layerId}_${MathUtil.guid()}`,
            layerName
          }

          itemRes.tableData = Object.keys(currentTableData).filter(key => {
            let bufferKey = key.toUpperCase()
            return bufferKey !== 'OBJECTID' && bufferKey !== 'SHAPE' && bufferKey !== 'SHAPE.AREA' && bufferKey !== 'SHAPE.LEN' && bufferKey !== 'X' && bufferKey !== 'Y'
          }).map(key => {
            return { label: key, value: currentTableData[key] }
          })

          return itemRes
        })

        data.activeName = data.tabsData[0].layerId.toString()

        let geometryList = getGeometryListByQueryResult({ res: onlyRes, merge: true })
        highlightByGeometryList({ view, geometryList, zoom: false })

        return content.refs.tabs.$el
      }

      const beforeQuery = () => {
        data.loading = true

      }

      const afterQuery = () => {
        data.loading = false

      }

      const getQueryConfig = ({ queryType, inputValue }) => {

        let { view } = data

        let result = {
          view,
          idList: [],
          outFields: [],
          where: [],
          returnGeometry: [],
          subLayerIds: []
        }

        switch (queryType) {

          case 'zzzy' :
            let whereValue = `FAMILY LIKE '%${inputValue}%' or GENUS LIKE '%${inputValue}%' or NAME LIKE '%${inputValue}%' or IDENTIFY_USER_ID LIKE '%${inputValue}%' or LOCATION LIKE '%${inputValue}%' or CLT_USER_ID LIKE '%${inputValue}%' or GENUS LIKE '%${inputValue}%'`
            result.idList.push('GermplasmResourceService')
            result.outFields.push({ parentId: 'GermplasmResourceService', value: ['*'] })
            result.where.push({ parentId: 'GermplasmResourceService', value: whereValue })
            result.returnGeometry.push({ parentId: 'GermplasmResourceService', value: true })
            result.subLayerIds.push({ parentId: 'GermplasmResourceService', value: [0] })
            break

          case 'sys' :
            result.idList.push('LaboratoryService')
            result.outFields.push({ parentId: 'LaboratoryService', value: ['*'] })
            result.where.push({ parentId: 'LaboratoryService', value: `NAME like '%${inputValue}%'` })
            result.returnGeometry.push({ parentId: 'LaboratoryService', value: true })
            result.subLayerIds.push({ parentId: 'LaboratoryService', value: [0] })
            break

          case 'tr' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'sf' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          default:
            break
        }

        return result

      }

      const attQuery = async(config) => {
        let { view } = data
        if (!view) return
        data.loading = true
        let res = await queryResultsByUrls(getQueryConfig(config))

        let geometryList = getGeometryListByQueryResult({ res, merge: true })

        if (!geometryList?.length) {
          data.loading = false
          Message.warning('没有查询结果')
          removeHighlight(view)
          return
        }

        highlightByGeometryList({ view, geometryList: getGeometryListByQueryResult({ res, merge: true }), zoom: true })
        data.loading = false
      }

      const load = view => {
        if (view?.mapView) {
          data.view = view.mapView
          data.loading = false
          content.emit('load', view.mapView)
        }
      }

      return { ...toRefs(data), load, attQuery, queryBackFun, beforeQuery, afterQuery }
    }
  }
</script>

<style scoped lang="scss">
  $full: 100%;
  .l-p-c-root {
    width: 100%;
    height: 100%;
    position: relative;

    .query-container {
      position: absolute;
      top: 50px;
      z-index: 20;
      display: flex;
      flex-direction: row;

      .el-input-group__append {
        border: none;
      }
    }
  }
</style>
